package com.example.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.ApiResult;
import com.example.controller.frontend.SmsController;
import com.example.dto.UserDTO;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.vo.ForgotPwdVO;
import com.example.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private SmsController smsController;

    /**
     * 客户端用户注册
     */
    @Override
    public boolean register(String phoneNumber, String password, String nickName) {
        boolean register = userMapper.register(phoneNumber, password, nickName);
        return register;
    }


    @Transactional
    @Override
    public ApiResult adminLogin(UserVO userVO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone_number",userVO.getUsername());
        User userEntity = userMapper.selectOne(queryWrapper);
        System.out.println("addsasa"+userEntity);
        if (userEntity == null) {
            return ApiResult.fail("此账号不存在！");
        }
        else if(! userEntity.getPassword().equals(userVO.getPassword())){
            return ApiResult.fail("登录密码错误！");
        }
        else if(userEntity.getUserStatus() == 1){
            return ApiResult.fail("登录失败，此账号已被禁用！");
        }
        else if(userEntity.getUserType() != 0){
            return ApiResult.fail("登录失败，您不是后台管理员！");
        }
        else {
            String token = UUID.fastUUID().toString(true);
            UserDTO adminDTO = new UserDTO();
            adminDTO.setUserId(userEntity.getId());
            adminDTO.setPhoneNumber(userEntity.getPhoneNumber());
            adminDTO.setNickName(userEntity.getNickName());
            adminDTO.setToken(token);
            adminDTO.setVisitCount(userEntity.getVisitCount());
            adminDTO.setAvatarUrl(userEntity.getAvatarUrl());
            Object adminObj = redisTemplate.opsForValue().get(token);
            if(adminObj == null) {
                redisTemplate.opsForValue().set(token,adminDTO,7,TimeUnit.DAYS);
            }
            return ApiResult.ok(adminDTO,"恭喜您，登录成功！");
        }
    }

    @Transactional
    @Override
    public ApiResult forgotPassword(ForgotPwdVO forgotPwdVO) {
        Pattern p = Pattern.compile("^1[1345789]\\d{9}$");
        Matcher m = p.matcher(forgotPwdVO.getPhoneNumber());
        if (!m.matches()) {
            return ApiResult.fail("手机格式不正确");
        }
        ApiResult apiResult = smsController.checkPhoneLogin(forgotPwdVO.getPhoneNumber(), forgotPwdVO.getInputCode());
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("phone_number", forgotPwdVO.getPhoneNumber());
        updateWrapper.set("password", forgotPwdVO.getPassword());
        boolean b = update(updateWrapper);
        if (b == true) {
            if (apiResult.isSuccess() == true) {
                return ApiResult.ok(b);
            }else {
                return apiResult;
            }
        }
        return ApiResult.fail("手机号不存在");
    }

}
